const WebSocketServer = require('websocket').server;
const http = require('http')

LB.HELPER.WSF = class {
    static k;
    static iv;
    static ws;
    static name;
    constructor(name,url,k,iv){
        this.name = name;
        this.url = url;
        this.k = k;
        this.iv = iv;
        var ws_rgx = new RegExp(/(.*)(:)(.*|)/,'g')
        var WebSocketAddress = url.replace(ws_rgx,'$1')
        var WebSocketPort = url.replace(ws_rgx,'$3')
        var server = http.createServer((request, response)=>{});
        server.listen(WebSocketPort,WebSocketAddress, function() {
            LB.log.ok("当前工作模式：服务器模式");
            LB.log.ok("开始监听WebSocket：" + WebSocketAddress+":"+WebSocketPort)
        });
        this.ws = new WebSocketServer({httpServer: server});

        this.ws.on('request',(req)=>{   //WebSocket客户端连接成功

            var con = req.accept(null, req.origin);
            this.con = con;

            LB.log.ok("WebSocket连接成功");
            con.on('close', ()=>{
                LB.log.warn("WebSocket连接断开");
                //LB.bot.toMgmtGroup("与服务器断开连接");
            });
            con.on('message',(m)=>{
                LB.MAIN.WEBSOCKET.forEach(element => {
                    try{
                        element(this.name,m.utf8Data);
                    }catch(err){
                        LB.log.error('[WebSocket] 出现异常（'+err.message+')');
                    }
                });
            });

            con.on('error', (err)=>{
                LB.log.error("WebSocket连接错误（" + err.toString()+')');
            });
        });

        this.ws.on('connectFailed',(err)=>{
            LB.log.error("WebSocket连接失败（" + err.toString()+`）`);
        });
    };

    getServerInfo(){
        try{
            //LB.log.info('[WebSocket]','<Group> ->',`<${this.name}>`,"(type:runcmdrequest)");
            this.con.sendUTF(LB.HELPER.WSE.getsrvinfopack(this.k,this.iv));
        }catch(err){
            LB.log.error('[WebSocket]',`服务器 ${this.name} 连接中断:${err}`);
            LB.bot.toMgmtGroup(LB.HELPER.MSG.getGroupEvent("server_connect_error"))
        }
    }

    runCMD(m){
        try{
            //LB.log.info('[WebSocket]','<Group> ->',`<${this.name}>`,"(type:runcmdrequest)");
            this.con.sendUTF(LB.HELPER.WSE.runcmdPack(this.k,this.iv,m));
        }catch(err){
            LB.log.error('[WebSocket]',`服务器 ${this.name} 连接中断:${err}`);
            LB.bot.toMgmtGroup(LB.HELPER.MSG.getGroupEvent("server_connect_error"))
        }
    };

    sendText(m){
        try{
            //LB.log.info('[WebSocket]','<Group> ->',`<${this.name}>`,"(type:sendtext)");
            this.con.sendUTF(LB.HELPER.WSE.sendtextPack(this.k,this.iv,m));
        }catch(err){
            LB.log.error('[WebSocket]',`服务器 ${this.name} 连接中断，无法发送WebSocket消息:${err}`);
        }
    }
}